import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetTest {
    public static void main(String[] args) {
        TreeSet<Student> treeSet = new TreeSet<Student>(new ComparatorByName());

//        treeSet.add("111");
//        treeSet.add("222");
//        treeSet.add("222");
//        treeSet.add("333");
//        treeSet.add("aaa");
//        treeSet.add("333");
//        treeSet.add("444");
//        treeSet.add("555");

        //通过遍历看出，是按照字典排序且不重复的
//        Iterator it = treeSet.iterator();
//        while(it.hasNext()){
//            System.out.println(it.next());
//        }

        //Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to java.lang.Comparable
        treeSet.add(new Student("aaa",12));
        treeSet.add(new Student("bbb",13));
        treeSet.add(new Student("ccc",14));
        treeSet.add(new Student("ccc",15));
        treeSet.add(new Student("ccc",15));
        treeSet.add(new Student("aaa",15));

        //通过遍历看出，是按照字典排序且不重复的
        Iterator it_2 = treeSet.iterator();
        while(it_2.hasNext()){
            Student p = (Student)it_2.next();
            System.out.println(p);
        }
    }
}

/**
 * 实现Comparable接口
 */
class Student /*implements Comparable*/{
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

//    @Override
//    public int compareTo(Object o) {
//        Student s = (Student)o;
//        int temp = this.age - s.age;
//        return temp==0?this.name.compareTo(s.name):temp;
//    }
}

/**
 * 根据Student类的name进行排序的比较器
 */
class ComparatorByName implements Comparator{
    @Override
    public int compare(Object o1, Object o2) {
        Student s1 = (Student)o1;
        Student s2 = (Student)o2;
        int temp = s1.getName().compareTo(s2.getName());
        return temp == 0 ? s1.getAge()-s2.getAge() : temp;
    }
}